from django.shortcuts import render

from chat.models import FansMessage, AtMessage
from forum.models import Comment
from utils.decorators import check_login
from utils.common_utils import *


@check_login
def get_fansmessage_list(request):
    account_id = request.session.get('account_id', '')
    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    fm_count = FansMessage.objects.filter(receive_id=account_id).count()
    p = Pagination(page=page, per_page=per_page, total=fm_count)
    fm_list = FansMessage.objects.filter(receive_id=account_id).order_by("-created_on")[p.offset:p.offset + per_page]
    result_list = []
    account_mg = AccountManager()
    for item in fm_list:
        created_by_id = item.created_by_id
        account_info = account_mg.get_account_by_id(created_by_id)
        tmp = {
            "id": item.id,
            "nick_name": account_info.nick_name,
            "create_id": created_by_id,
            "created_time": item.created_on
        }
        result_list.append(tmp)
    FansMessage.objects.filter(receive_id=account_id, is_read=False).update(is_read=True)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})

@check_login
def get_atmessage_list(request):
    account_id = request.session.get('account_id', '')
    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    am_count = AtMessage.objects.filter(receive_id=account_id).count()
    p = Pagination(page=page, per_page=per_page, total=am_count)
    am_list = AtMessage.objects.filter(receive_id=account_id).order_by("-created_on")[p.offset:p.offset + per_page]
    result_list = []
    account_mg = AccountManager()
    for item in am_list:
        comment_id = item.comment_id
        try:
            cm = Comment.objects.get(id=comment_id)
            created_by_id = item.created_by_id
            account_info = account_mg.get_account_by_id(created_by_id)
            tmp = {
                "id": item.id,
                "comment_id": comment_id,
                "nick_name": account_info.nick_name,
                "created_time": item.created_on,
                "topic_id": cm.topic_id,
                "category": cm.category,
            }
            result_list.append(tmp)
        except Comment.DoesNotExist:
            item.delete()
            continue
    AtMessage.objects.filter(receive_id=account_id, is_read=False).update(is_read=True)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})
